<template>
  <div class="model-loading-demo">
    <div class="demo-header">
      <h1>🚀 模型加载性能优化演示</h1>
      <p>对比传统加载与优化后加载的性能差异</p>
    </div>
    
    <div class="demo-controls">
      <a-button-group>
        <a-button @click="loadWithOptimization" type="primary" :loading="optimizedLoading">
          <template #icon><icon-rocket /></template>
          优化加载 (推荐)
        </a-button>
        <a-button @click="loadWithoutOptimization" type="outline" :loading="normalLoading">
          <template #icon><icon-clock-circle /></template>
          传统加载
        </a-button>
        <a-button @click="clearCache" type="outline">
          <template #icon><icon-delete /></template>
          清理缓存
        </a-button>
      </a-button-group>
    </div>
    
    <div class="demo-stats">
      <a-row :gutter="16">
        <a-col :span="8">
          <div class="stat-card">
            <div class="stat-title">🏎️ 优化加载</div>
            <div class="stat-value">{{ optimizedStats.time }}ms</div>
            <div class="stat-desc">
              缓存命中: {{ optimizedStats.cacheHit ? '✅' : '❌' }}<br>
              分帧处理: ✅<br>
              内存优化: ✅
            </div>
          </div>
        </a-col>
        <a-col :span="8">
          <div class="stat-card">
            <div class="stat-title">🐌 传统加载</div>
            <div class="stat-value">{{ normalStats.time }}ms</div>
            <div class="stat-desc">
              缓存命中: ❌<br>
              分帧处理: ❌<br>
              内存优化: ❌
            </div>
          </div>
        </a-col>
        <a-col :span="8">
          <div class="stat-card">
            <div class="stat-title">📊 性能提升</div>
            <div class="stat-value">{{ performanceImprovement }}%</div>
            <div class="stat-desc">
              内存使用: {{ memoryUsage }}MB<br>
              缓存大小: {{ cacheSize }}MB<br>
              加载次数: {{ loadCount }}
            </div>
          </div>
        </a-col>
      </a-row>
    </div>
    
    <div class="demo-logs">
      <h3>📝 性能日志</h3>
      <div class="log-container">
        <div 
          v-for="(log, index) in logs" 
          :key="index" 
          class="log-item"
          :class="log.type"
        >
          <span class="log-time">{{ log.time }}</span>
          <span class="log-message">{{ log.message }}</span>
        </div>
      </div>
    </div>
    
    <div class="optimization-features">
      <h3>🔧 优化特性说明</h3>
      <a-row :gutter="16">
        <a-col :span="12">
          <div class="feature-card">
            <h4>🏗️ 异步分帧处理</h4>
            <p>将模型解析和材质处理分散到多个帧中执行，避免阻塞主线程，确保页面交互响应正常。</p>
            <ul>
              <li>每帧处理限定数量的网格</li>
              <li>使用requestAnimationFrame调度</li>
              <li>进度反馈和中断支持</li>
            </ul>
          </div>
        </a-col>
        <a-col :span="12">
          <div class="feature-card">
            <h4>💾 智能缓存机制</h4>
            <p>基于LRU策略的模型缓存，支持内存限制和自动清理，大大提升重复加载速度。</p>
            <ul>
              <li>100MB缓存限制</li>
              <li>LRU自动清理策略</li>
              <li>模型克隆和材质隔离</li>
            </ul>
          </div>
        </a-col>
        <a-col :span="12">
          <div class="feature-card">
            <h4>🧠 内存管理</h4>
            <p>自动释放几何体、材质和贴图资源，防止内存泄漏，优化长时间运行的应用。</p>
            <ul>
              <li>自动资源释放</li>
              <li>WebGL上下文清理</li>
              <li>内存使用监控</li>
            </ul>
          </div>
        </a-col>
        <a-col :span="12">
          <div class="feature-card">
            <h4>⚡ 材质优化</h4>
            <p>智能材质处理和PBR转换，修复常见的渲染问题，提升视觉效果。</p>
            <ul>
              <li>黑色材质自动修复</li>
              <li>PBR材质转换</li>
              <li>贴图优化和压缩</li>
            </ul>
          </div>
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { fbxModelCache } from '@/utils/fbxModelCache.js'
import { asyncModelProcessor } from '@/utils/asyncModelProcessor.js'
import {
  IconRocket,
  IconClockCircle,
  IconDelete
} from "@arco-design/web-vue/es/icon"

// 响应式状态
const optimizedLoading = ref(false)
const normalLoading = ref(false)
const logs = ref([])
const loadCount = ref(0)

// 性能统计
const optimizedStats = ref({
  time: 0,
  cacheHit: false
})

const normalStats = ref({
  time: 0,
  cacheHit: false
})

// 计算属性
const performanceImprovement = computed(() => {
  if (normalStats.value.time === 0) return 0
  return Math.round((normalStats.value.time - optimizedStats.value.time) / normalStats.value.time * 100)
})

const memoryUsage = computed(() => {
  // 模拟内存使用计算
  return (performance.memory?.usedJSHeapSize / 1024 / 1024 || 50).toFixed(1)
})

const cacheSize = computed(() => {
  const stats = fbxModelCache.getCacheStats()
  return stats.cacheSizeMB
})

// 添加日志
const addLog = (message, type = 'info') => {
  logs.value.unshift({
    time: new Date().toLocaleTimeString(),
    message,
    type
  })
  
  // 限制日志数量
  if (logs.value.length > 50) {
    logs.value.pop()
  }
}

// 优化加载
const loadWithOptimization = async () => {
  if (optimizedLoading.value) return
  
  optimizedLoading.value = true
  loadCount.value++
  
  const startTime = performance.now()
  addLog('🚀 开始优化加载...', 'success')
  
  try {
    // 检查缓存
    const cacheStats = fbxModelCache.getCacheStats()
    const initialCacheHits = cacheStats.hits
    
    addLog('📦 检查模型缓存...')
    
    // 模拟FBX模型加载
    const MODEL_PATH = '/models/port.fbx' // 示例路径
    
    await fbxModelCache.loadModel(MODEL_PATH, {
      enableCaching: true,
      onProgress: (percentage) => {
        addLog(`📊 加载进度: ${Math.round(percentage)}%`)
      },
      onProcessProgress: (percentage) => {
        addLog(`⚙️ 处理进度: ${Math.round(percentage)}%`)
      }
    })
    
    // 检查是否命中缓存
    const finalCacheStats = fbxModelCache.getCacheStats()
    const cacheHit = finalCacheStats.hits > initialCacheHits
    
    const endTime = performance.now()
    const loadTime = Math.round(endTime - startTime)
    
    optimizedStats.value = {
      time: loadTime,
      cacheHit
    }
    
    addLog(`✅ 优化加载完成 (${loadTime}ms)${cacheHit ? ' - 缓存命中!' : ''}`, 'success')
    addLog(`📈 缓存统计: ${finalCacheStats.cachedModels} 个模型, 命中率 ${finalCacheStats.hitRate.toFixed(1)}%`)
    
  } catch (error) {
    addLog(`❌ 优化加载失败: ${error.message}`, 'error')
  } finally {
    optimizedLoading.value = false
  }
}

// 传统加载
const loadWithoutOptimization = async () => {
  if (normalLoading.value) return
  
  normalLoading.value = true
  loadCount.value++
  
  const startTime = performance.now()
  addLog('🐌 开始传统加载...', 'warning')
  
  try {
    // 模拟传统同步加载
    addLog('📦 下载模型文件...')
    await new Promise(resolve => setTimeout(resolve, 1000 + Math.random() * 2000))
    
    addLog('⚙️ 同步处理材质...')
    await new Promise(resolve => setTimeout(resolve, 800 + Math.random() * 1200))
    
    addLog('🔧 计算几何体...')
    await new Promise(resolve => setTimeout(resolve, 500 + Math.random() * 1000))
    
    const endTime = performance.now()
    const loadTime = Math.round(endTime - startTime)
    
    normalStats.value = {
      time: loadTime,
      cacheHit: false
    }
    
    addLog(`✅ 传统加载完成 (${loadTime}ms)`, 'warning')
    addLog('⚠️ 注意: 传统加载可能导致页面卡顿')
    
  } catch (error) {
    addLog(`❌ 传统加载失败: ${error.message}`, 'error')
  } finally {
    normalLoading.value = false
  }
}

// 清理缓存
const clearCache = () => {
  fbxModelCache.clearCache()
  asyncModelProcessor.clear()
  addLog('🗑️ 缓存已清理', 'info')
  
  // 重置统计
  optimizedStats.value = { time: 0, cacheHit: false }
  normalStats.value = { time: 0, cacheHit: false }
}
</script>

<style scoped>
.model-loading-demo {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
  color: white;
}

.demo-header {
  text-align: center;
  margin-bottom: 30px;
}

.demo-header h1 {
  font-size: 2.5rem;
  margin-bottom: 10px;
  color: white;
}

.demo-header p {
  font-size: 1.1rem;
  opacity: 0.9;
}

.demo-controls {
  text-align: center;
  margin-bottom: 30px;
}

.demo-stats {
  margin-bottom: 30px;
}

.stat-card {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 20px;
  text-align: center;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.stat-title {
  font-size: 1.1rem;
  margin-bottom: 10px;
  font-weight: 600;
}

.stat-value {
  font-size: 2.5rem;
  font-weight: bold;
  margin-bottom: 10px;
  color: #4facfe;
}

.stat-desc {
  font-size: 0.9rem;
  opacity: 0.8;
  line-height: 1.5;
}

.demo-logs {
  margin-bottom: 30px;
}

.demo-logs h3 {
  margin-bottom: 15px;
  font-size: 1.3rem;
}

.log-container {
  background: rgba(0, 0, 0, 0.3);
  border-radius: 8px;
  padding: 15px;
  max-height: 300px;
  overflow-y: auto;
  font-family: 'Courier New', monospace;
}

.log-item {
  margin-bottom: 8px;
  padding: 5px 10px;
  border-radius: 4px;
  font-size: 0.9rem;
}

.log-item.success {
  background: rgba(82, 196, 26, 0.2);
  border-left: 3px solid #52c41a;
}

.log-item.warning {
  background: rgba(250, 173, 20, 0.2);
  border-left: 3px solid #faad14;
}

.log-item.error {
  background: rgba(255, 77, 79, 0.2);
  border-left: 3px solid #ff4d4f;
}

.log-item.info {
  background: rgba(24, 144, 255, 0.2);
  border-left: 3px solid #1890ff;
}

.log-time {
  color: #888;
  margin-right: 10px;
}

.optimization-features {
  margin-top: 30px;
}

.optimization-features h3 {
  margin-bottom: 20px;
  font-size: 1.3rem;
  text-align: center;
}

.feature-card {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 16px;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.feature-card h4 {
  margin-bottom: 10px;
  color: #4facfe;
  font-size: 1.1rem;
}

.feature-card p {
  margin-bottom: 15px;
  opacity: 0.9;
  line-height: 1.6;
}

.feature-card ul {
  margin: 0;
  padding-left: 20px;
}

.feature-card li {
  margin-bottom: 5px;
  opacity: 0.8;
}
</style>


























